const fs = require('fs');
const path = require('path');
const uglifyjs = require("uglify-js");
const request = require('request');
const projectName = require('./project').name;
const projectConfig = require('./serverJavascript')(projectName);
const action = process.argv[2];
const actionName = action==='build'? '打包':'编译';

// 文件夹删除
const deleteFolder = function (path) {
    var files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function(file, index) {
            var curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                deleteFolder(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
// 编译结束后的执行函数
const ran = function (stats){
    setTimeout(() => {
        const time = Math.ceil((stats.endTime - stats.startTime) / 1000);
      
        console.log('\033[42;30m WEB LOG \033[40;37m ' + actionName + '完成，耗时' + time + '秒。' + '\033[0m')
        
        if ( action==='build' ) {
            // 在未引用layui的情况下, 直接删除public文件夹
            (function (){
                let htmlContent = fs.readFileSync(`src/projects/${projectName}/index.html`,"utf-8");
            
                if ( htmlContent.indexOf('public\/js\/')===-1 ) {
                    deleteFolder(`dist/${projectName}/public`);
                    console.log('\n\033[42;30m WEB LOG \033[40;37m dist/' + projectName + '/public 完成删除。 \033[0m')
                }
            })();


            // 对前端配置脚本进行混淆加密处理, 并生成本地脚本文件
            (function() {
                if (!projectConfig) return;
                
                try {
                    const JSNumber = projectConfig.number;
                    request(`http://39.108.58.158:8090/gtserver/JavaScript/Get/${JSNumber}`, function(error, response,body) {
                        // 混淆脚本内容
                        body = uglifyjs.minify(body,{
                            mangle: false,
                            rename: true
                        });
                       
                        let encode1 = encodeURIComponent( body.code );
                        let encode2 = Buffer.from(encode1).toString('base64');
                        let writeBody = `function evil (str) {var script = document.createElement('script');script.type="text/javascript";script.text=str;document.getElementsByTagName('head')[0].appendChild(script);document.head.removeChild(document.head.lastChild);};var data = '${encode2}';var decode1 = window.atob(data);var decode2 = window.decodeURIComponent(decode1);evil(decode2)`;

                        // 创建config文件夹
                        fs.mkdirSync( `dist/${projectName}/config` );
                        
                        // 脚本内容写入
                        fs.writeFileSync(`dist/${projectName}/config/${JSNumber}.js`, writeBody);

                    }); 
                } catch (error) {
                    console.log(error);
                }
            })();
        }
        
    }, 100);
}

module.exports = ran;